﻿using rbac.domain.Entity;
using rbac.domain.Interface;

namespace rbac.domain.Impl;

public class RolePermissionRepository:IRolePermissionRepository
{
    private readonly RbacContext _context;

    public RolePermissionRepository(RbacContext context)
    {
        _context = context;
    }

    public int DistributeRolePermission(int roleId, List<int> permissionIdList)
    {
        if (permissionIdList.Count<=0)
        {
            return 0;
        }

        // 最新的权限列表我想厂商会哈哈哈刚刚一个合格好尴尬
        List<RolePermission> list = permissionIdList.Select(p=>new RolePermission
        {
            RoleId = roleId,
            PermissionId = p
        }).ToList();
        
        // //查询原有的权限列表111111
        var oldPermissions = _context.RolePermissions.Where(p=>p.RoleId ==  roleId);
        // // 移除原有的权限
        _context.RolePermissions.RemoveRange(oldPermissions);
        _context.RolePermissions.AddRange(list);
        
        
        
        // 获取需要被移除的权限
        // var needDeleteList = oldPermissions.Except(list);// 取差集
        // _context.RolePermissions.RemoveRange(needDeleteList);
        // var needAddList = list.Except(oldPermissions); // 新增的权限
        // _context.RolePermissions.AddRange(needAddList);


        return _context.SaveChanges();

    }

    public List<Permission> GetPermissionByRoleId(int roleId)
    {
        // 根据角色Id获取权限IdList
        var permissionIdList = _context.RolePermissions.Where(p=>p.RoleId == roleId).Select(p=>p.PermissionId);

        // 权限Id List 去  Permission表中获取详细数据
        return _context.Permissions.Where(p=>permissionIdList.Contains(p.Id)).ToList();
    }
}